package com.paic.icore.test.demo.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.paic.icore.test.demo.util.ResponseResult;

import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Order(1000)
@ControllerAdvice(basePackages = "com")
public class ResponseResultAdvice implements ResponseBodyAdvice {

	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		// return
		// MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		if (null != body) {
			if (body instanceof String) {
				String bodyStr = (String) body;
				if (bodyStr.contains("\"code\":") && bodyStr.contains("\"msg\":")) {
					return body;
				}
				return JSON.toJSONString(new ResponseResult(body));
			}
			// 已经是返回标准不再封装
			if (body instanceof ResponseResult) {
				return body;
			}
			String returnStr = JSONObject.toJSONString(body);// 如果body 包含code
																// msg ,不再次封装一次
			if (returnStr.contains("\"code\":") && returnStr.contains("\"msg\":")) {
				return body;
			}
		}
		return new ResponseResult(body);
	}

}
